const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::upload');
const os = require('os');
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();
exports = module.exports = router;

const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectID;

const uploader = require(global.prefixPath + '/qiniu/uploader');
const file_service = require(global.prefixPath + '/services/file');

router.get('/upload', async (ctx, next) => {

	let html = "<form method='post' enctype='multipart/form-data'>"
		+ "<input type='file' name='upload_file' accept='.png'>"
		+ "<button>upload picture</button>"
		+ "</form>";

	ctx.type = "text/html;charset=utf-8";
	ctx.body = html;

});

router.post('/upload', async (ctx, next) => {
	console.log('post upload: ');

	try {
		const datas = [];
		const files = ctx.request.body.files || {};

		for (let key in files) {
			const file = files[key];
			const file_size = file.size;
			const file_name = file.name;
			const file_type = file.type;
			const postfix = file_name.substr(file_name.lastIndexOf('.'));
			const id = new ObjectId();
			const file_key = id.toString('Hex') + postfix;
			const reader = fs.createReadStream(file.path);
			let upload_result = await uploader.uploadByStream(file_key, reader);
			datas.push({
				"_id": id,
				"contentType": file_type,
				"createdAt": new Date(),
				"fileName": file_name,
				"isDeleted": false,
				"postfix": postfix,
				"sizeInBytes": file_size,
				"hash": upload_result.hash,
				"key": upload_result.key,
				"path": upload_result.path,
				"token": upload_result.token,
				"uploadTime": new Date(),
			})
		}
		let result = await file_service.insert(datas);
		ctx.body = result;
	} catch(e) {
		
		console.log(e);
	}

});